package com.hly.utils;

import javafx.util.Pair;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 流程：
 * 第一步：先把中文的翻译，公共模块和业务个模块的中文strings.xml文件，放在同一个strings.xml文件中，记得检测有些模块是默认使用了英文的，那么理应英文的也是相当于中文，也要放入strings.xml中
 * 第二步：根据整合好的strings.xml文件，调用程序去检测一遍，主要是针对有相同的name命名，和值存在相同的情况，再次整理后保存
 * 第三步：xlsx中需要翻译的和strings.xml去对比，遍历每一条去替换，然后保存，其他语言的直接保存
 * 第四步：把处理好的，下载到本地，对应到每一个文件夹当中
 */
public class RedXml {

    /**
     * 是否清除注释
     */
    private static boolean isClearExegesis = true;
    private static String filePath = "D:\\tmp\\strings.xml";

    private static StringBuilder sb = new StringBuilder();
    private static LinkedHashMap<String, String> mapName = new LinkedHashMap<>();
    private static LinkedHashMap<String, String> mapValue = new LinkedHashMap<>();

    private static LinkedHashMap<String, List<XmlBean>> languageXmlBeanMap = new LinkedHashMap<>();
    private static int readCount;
    private static int noReadCount;


    private static String mainLanguage = "汉语";

    //    private static String filePathRoot = "D:\\tmp\\"; // 指定 xlsx 文件的路径
//    private static String fileName = "工作簿 (1).xlsx"; // 指定 xlsx 文件的路径
    public static void main(String[] args) {
        //--clear --stringsPath=D:\tmp\strings.xml --fyWorldPath=D:\tmp\工作簿 (1).xlsx
        String xlsxPath = "";
        if (null != args && args.length > 0) {
            for (String arg : args) {
                if ("--clear".equals(arg)) {
                    isClearExegesis = true;
                } else if ("--no-clear".equals(arg)) {
                    isClearExegesis = false;
                } else if (arg.contains("--stringsPath=")) {
                    filePath = arg.split("--stringsPath=")[1];
                } else if (arg.contains("--xlsxPath=")) {
                    xlsxPath = arg.split("--xlsxPath=")[1];
                } else if (arg.equals("isPrintStringsXml")) {
                    FyUtils.isPrintStringsXml = true;
                } else if (arg.equals("isPrintSpecifications")) {
                    FyUtils.isPrintSpecifications = true;
                }
            }
        }
        step1(filePath);
        step2(xlsxPath);
        System.err.println(FyUtils.errorStringBuffer.toString());
        System.err.println("存在%s的翻译，需要每个语言包去核对，并且代码中使用String.format(a,b)或者activity.getString(a,b)或者fragment.getString(a,b)");
        FyUtils.fuhaoList.forEach(System.err::println);

        //如何认为空呢？：：：：里面没有一条是<string></string>这样的 完成
        //mainString  是空的情况：直接生成翻译给到的 完成
        //mainString  不是空的情况：需要把他们混合生成，混合生成有个问题，假如一样的key，值不一样，需要去替换？
        //如何替换，需要把旧的值先拿到，然后输出到文件，然后去拿翻译的去插入，如果存在key则替换，如果不存在，则新增
    }

    private static void step2(String xlsxPath) {//中文的用原始的，然后去匹配，有就修改，没有就不管，其他语言的，不需要过滤，翻译有什么，就生成什么数据即可，然后都保存
        //根据xlsx中定义好的key，遍历出来，找到strings.xml中对应的那一行内容，然后去保存
        if (!"".equals(xlsxPath)) {
            //从翻译文档中读取到路径和写入的内容
            Map<String, LinkedHashMap<String, XmlBean>> xmlBeanMap = FyUtils.handlerContent(xlsxPath);
            for (Map.Entry<String, LinkedHashMap<String, XmlBean>> xlsxEntry : xmlBeanMap.entrySet()) {
                if (mainLanguage.equals(xlsxEntry.getKey())) {
                    if (!FyUtils.isNullXml) {
                        StringBuilder sb = new StringBuilder();
                        StringBuilder modifySB = new StringBuilder();
                        sb.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>").append("\n");
                        sb.append("<resources xmlns:tools=\"http://schemas.android.com/tools\">").append("\n");
                        sb.append("\t").append("<!-- " + xlsxEntry.getKey() + "翻译 -->").append("\n");
                        String keyTemp = "";
                        Map<String, XmlBean> oldBeanMap = new HashMap<>();
                        for (int i = 0; i < languageXmlBeanMap.get(mainLanguage).size(); i++) {
//                            System.out.println("旧的值----" + languageXmlBeanMap.get(mainLanguage).get(i).getFullContent());
                            XmlBean xmlBean = languageXmlBeanMap.get(mainLanguage).get(i);
                            keyTemp = xmlBean.getName();
                            if (!xlsxEntry.getValue().containsKey(languageXmlBeanMap.get(mainLanguage).get(i).getName())) {
                                sb.append("\t").append(languageXmlBeanMap.get(mainLanguage).get(i).getFullContent()).append("\n");
                            } else {
                                oldBeanMap.put(keyTemp, xmlBean);
                            }
                        }
                        sb.append("\t").append("<!-- 下面是新增的内容" + new SimpleDateFormat("yyyy/mm/dd HH:mm").format(new Date()) + " -->").append("\n");
                        for (Map.Entry<String, XmlBean> addItem : xlsxEntry.getValue().entrySet()) {
                            if (!oldBeanMap.containsKey(addItem.getValue().getName())) {
                                sb.append("\t").append(addItem.getValue().getFullContent()).append("\n");
                            }
                        }
                        sb.append("\t").append("<!-- 下面是更新的内容" + new SimpleDateFormat("yyyy/mm/dd HH:mm").format(new Date()) + " -->").append("\n");
                        for (Map.Entry<String, XmlBean> updateItem : oldBeanMap.entrySet()) {
                            XmlBean xmlBean = updateItem.getValue();
                            modifySB.append("\t").append(xmlBean.getFullContentTemp().replace(xmlBean.getTag(), xlsxEntry.getValue().get(xmlBean.getName()).getContent())).append("\n");
                        }
                        sb.append(modifySB);
//                        for (int i = 0; i < languageXmlBeanMap.get(mainLanguage).size(); i++) {
//                            XmlBean xmlBean = languageXmlBeanMap.get(mainLanguage).get(i);
//                            keyTemp = xmlBean.getName();
//                            for (Map.Entry<String, XmlBean> addItem : xlsxEntry.getValue().entrySet()) {
//                                if (addItem.getValue().getName().equals(keyTemp)) {
////                                    sb.append("\t").append(addItem.getValue().getFullContent()).append("\n");
//                                    sb.append("\t").append(xmlBean.getFullContentTemp().replace(xmlBean.getTag(), xlsxEntry.getValue().get(xmlBean.getName()).getContent())).append("\n");
//                                    System.out.println("替换了" + keyTemp + "新的值是：" + xlsxEntry.getValue().get(xmlBean.getName()).getContent() + "----替换后整体效果：" + xmlBean.getFullContentTemp().replace(xmlBean.getTag(), xlsxEntry.getValue().get(xmlBean.getName()).getContent()));
//                                    isFind = true;
//                                    break;
//                                } else {
//                                    sb.append("\t").append(addItem.getValue().getFullContent()).append("\n");
//                                }
//                            }
//                        }
                        sb.append("</resources>");
//                        System.out.println(sb.toString());
                        writeFile(xlsxEntry.getValue().values().stream().findFirst().get().getWritePath(), sb.toString());
                    } else {
                        StringBuilder sb = new StringBuilder();
                        sb.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>").append("\n");
                        sb.append("<resources xmlns:tools=\"http://schemas.android.com/tools\">").append("\n");
                        sb.append("\t").append("<!-- " + xlsxEntry.getKey() + "翻译 -->").append("\n");
//                        System.out.println("保存路径：" + );
                        String newFile = FyUtils.writeFilePathMap.get(mainLanguage);
//                        String newFile = FyUtils.writeFilePathMap.get(mainLanguage).replace("strings.xml","strings_add.xml");
                        for (Map.Entry<String, XmlBean> stringXmlBeanEntry : xlsxEntry.getValue().entrySet()) {
                            sb.append("\t").append(stringXmlBeanEntry.getValue().getFullContent()).append("\n");
                        }
                        sb.append("</resources>");
                        writeFile(newFile, sb.toString());
//                        System.out.println("\n--------------------------string.xml没有可以翻译的情况start----------------------------");
//                        System.out.println(sb.toString());
//                        System.out.println("--------------------------string.xml没有可以翻译的情况end----------------------------\n");
                    }
                } else {//其他语言 if ("英语".equals(xlsxEntry.getKey()))
                    if (xlsxEntry.getValue().size() > 0) {
                        StringBuilder sb = new StringBuilder();
                        sb.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>").append("\n");
                        sb.append("<resources xmlns:tools=\"http://schemas.android.com/tools\">").append("\n");
                        sb.append("\t").append("<!-- " + xlsxEntry.getKey() + "翻译 -->").append("\n");
                        System.out.println("输出语言：" + xlsxEntry.getKey());
                        LinkedHashMap<String, XmlBean> beanHashMap = xlsxEntry.getValue();
//                        String keyTemp = "";
                        for (Map.Entry<String, XmlBean> xmlBeanEntry : beanHashMap.entrySet()) {
//                            keyTemp = xmlBeanEntry.getKey();
                            if (FyUtils.keyNameMap.containsValue(xmlBeanEntry.getValue().getName())) {
//                                String fullContent = xmlBeanEntry.getValue().getFullContent();
                                if (TextUtils.isEmpty(xmlBeanEntry.getValue().getContent())) {
//                                    String newContent = xmlBeanMap.get(mainLanguage).get(xmlBeanEntry.getValue().getName()).getContent();
                                    System.out.println("替换了内容=" + xmlBeanMap.get(mainLanguage).get(xmlBeanEntry.getValue().getName()));
//                                    xmlBeanEntry.getValue().getFullContentTemp().replace(xmlBeanEntry.getValue().getTag(),newContent)
//                                    xmlBean.getFullContentTemp().replace(xmlBean.getTag(), xlsxEntry.getValue().get(xmlBean.getName()).getContent())
                                    sb.append("\t").append(xmlBeanMap.get(mainLanguage).get(xmlBeanEntry.getValue().getName())).append("\n");
                                } else {
                                    sb.append("\t").append(xmlBeanEntry.getValue().getFullContent()).append("\n");
                                }
//                                if (fullContent.contains("\"></string>")) {
//                                    sb.append("\t").append(xmlBeanEntry.getValue().getFullContentTemp().replace(xmlBeanEntry.getValue().getTag(),"这个是我替换的值")).append("\n");
//                                } else {
//                                    sb.append("\t").append(xmlBeanEntry.getValue().getFullContent()).append("\n");
//                                }
                            }
                        }
                        sb.append("</resources>");

//                    System.out.println(sb);
//                    System.out.println("路径：" + xlsxEntry.getValue().get(keyTemp).getWritePath());
                        writeFile(xlsxEntry.getValue().values().stream().findFirst().get().getWritePath(), sb.toString());
                    }
                    if (xlsxEntry.getValue().size() > 0) {
                    } else {
                        System.out.println("没有数据 " + xlsxEntry.getKey());
                    }
                }
            }
        }
    }

    private static void writeFile(String stringXmlPath, String stringXmlContent) {
        String stringXmlContentTemp = new String(stringXmlContent.getBytes(StandardCharsets.UTF_8));
        System.out.println("============================================================");
        System.out.println("");
        BufferedWriter bw = null;
        FileWriter fw = null;
        try {
            File file = new File(stringXmlPath);
            if (file.exists()) {
                file.delete();
            }
            fw = new FileWriter(file);
            bw = new BufferedWriter(fw);
            bw.write(stringXmlContentTemp, 0, stringXmlContentTemp.length());
            bw.flush();
            System.out.println("========================写入成功==========================" + stringXmlPath);
            System.out.println(stringXmlContentTemp);
        } catch (Exception e) {
            FyUtils.errorStringBuffer.append("写入失败：" + stringXmlPath).append("\n");
        } finally {
            try {
                if (null != bw) {
                    bw.close();
                }
            } catch (IOException e) {
            }
            try {
                if (null != fw) {
                    fw.close();
                }
            } catch (IOException e) {
            }
        }
    }

    /**
     * 检验文件
     *
     * @param filePath
     */
    private static void step1(String filePath) {
        readCount = 0;
        noReadCount = 0;
        File file = new File(filePath);
        FileInputStream in = null;
        BufferedReader bis = null;
        InputStreamReader inputStreamReader = null;
        try {
            in = new FileInputStream(file);
            inputStreamReader = new InputStreamReader(in);
            bis = new BufferedReader(inputStreamReader);
            String content = null;
            int count = 0;
            int unCount = 0;
            while ((content = bis.readLine()) != null) {
                if (content.equals("") || content.contains("\"http://schemas.android.com/tools\"") || content.contains("version=\"1.0\"") || content.contains("encoding=\"utf-8\"") || content.contains("</resources>")) {
                    unCount++;
                    continue;// || content.startsWith("<!--") || content.contains("<!--")
                }
                if (content.replace(" ", "").length() == 0) {
                    continue;
                }
                readStringTag(content);
                count++;
            }
            if (!languageXmlBeanMap.containsKey(mainLanguage) || null == languageXmlBeanMap.get(mainLanguage) || languageXmlBeanMap.get(mainLanguage).isEmpty()) {
                FyUtils.isNullXml = true;
                System.out.println("是否是空的xml内容：" + FyUtils.isNullXml);
            }
            printStringXmlContent(content);
            FyUtils.errorStringBuffer.append("===============================================================================================================").append("\n");
            FyUtils.errorStringBuffer.append("===============================请注意比对:一共读取了" + (count + unCount) + "行，实际输出 " + readCount + "，过滤了的行数：" + (noReadCount + unCount) + "==============================").append("\n");
            FyUtils.errorStringBuffer.append("===============================================================================================================").append("\n");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                bis.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                inputStreamReader.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                in.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 输出xml内容
     */
    private static void printStringXmlContent(String content) {
//        System.out.println("=======================printStringXmlContent======================" + content);
//        System.out.println("=======================输出xml内容======================");
//        System.out.println(sb.toString());
    }

    private static void readStringTag(String content) {
        if (content.contains("<!--") || content.startsWith("<!--") || content.endsWith("-->")) {
            if (!content.contains("//")) {
                if (!isClearExegesis) {
                    System.out.println(content);
                }
            }
            noReadCount++;
            return;
        }
        boolean isTranslatable = content.contains("translatable=\"false\"");
        boolean isExtraTranslation = content.contains("tools:ignore=\"ExtraTranslation\"");
        String replaceStr = content.replace(" translatable=\"false\"", "").replace("translatable=\"false\"", "").replace(" tools:ignore=\"ExtraTranslation\"", "").replace("tools:ignore=\"ExtraTranslation\"", "");
        Pair<String, String> tag = getTag(replaceStr);
        if (!isTranslatable && !isExtraTranslation) {
            printStringHtml(tag.getKey(), tag.getValue());
        } else if (isTranslatable && isExtraTranslation) {
            printStringHtmlTranslatableAndExtraTranslation(tag.getKey(), tag.getValue());
        } else if (isTranslatable) {
            printStringHtmlTranslatable(tag.getKey(), tag.getValue());
        } else if (isExtraTranslation) {
            printStringHtmlExtraTranslation(tag.getKey(), tag.getValue());
        }
        readCount++;
    }

    /**
     * 一定要正确的标签才能使用
     *
     * @param input
     * @return
     */
    private static Pair<String, String> getTag(String input) {
        String regex = "<string name=\"([^\"]+)\">(.*?)</string>";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(input);
        String name = null;
        String value = null;
        if (matcher.find()) {
            // 提取name属性的值
            name = matcher.group(1);
            // 提取string标签包裹的值
            value = matcher.group(2);
            //如果value是null或者是空的情况
//            if (null == value || "".equals(value)) {
//                value = "<(!-CustomContent-!)>";
//            }
        } else {
            throw new RuntimeException(input + "格式有误，请格式化后再操作，");
        }
        return new Pair<>(name, value);
    }

    private static void printStringHtml(String moduleName, String content) {
        String fullContent = "<string name=\"" + moduleName + "\">" + content + "</string>";
        sb.append(fullContent).append("\n");
        check(moduleName, content);
        putXmlBean(mainLanguage, new XmlBean("printStringHtml", moduleName, content, fullContent));
    }


    private static void printStringHtmlTranslatable(String moduleName, String content) {
        String fullContent = "<string name=\"" + moduleName + "\" translatable=\"false\">" + content + "</string>";
        sb.append(fullContent).append("\n");
        check(moduleName, content);
        putXmlBean(mainLanguage, new XmlBean("printStringHtmlTranslatable", moduleName, content, fullContent));
    }

    private static void printStringHtmlExtraTranslation(String moduleName, String content) {
        String fullContent = "<string name=\"" + moduleName + "\" tools:ignore=\"ExtraTranslation\">" + content + "</string>";
        sb.append(fullContent).append("\n");
        check(moduleName, content);
        putXmlBean(mainLanguage, new XmlBean("printStringHtmlExtraTranslation", moduleName, content, fullContent));
    }

    private static void printStringHtmlTranslatableAndExtraTranslation(String moduleName, String content) {
        String fullContent = "<string name=\"" + moduleName + "\" translatable=\"false\" tools:ignore=\"ExtraTranslation\">" + content + "</string>";
        sb.append(fullContent).append("\n");
        check(moduleName, content);
        putXmlBean(mainLanguage, new XmlBean("printStringHtmlTranslatableAndExtraTranslation", moduleName, content, fullContent));
    }

    private static void check(String moduleName, String content) {
        if (mapName.containsKey(moduleName)) {
            FyUtils.errorStringBuffer.append("异常：存在多个重复的keyName： " + "<string name=\"" + moduleName + "\">" + mapName.get(moduleName) + "</string>").append("\n");
        } else {
            mapName.put(moduleName, content);
        }
        if (mapValue.containsKey(content)) {
            FyUtils.errorStringBuffer.append("异常：存在多个重复的内容： " + "<string name=\"" + mapValue.get(content) + "\">" + content + "</string>").append("\n");
        } else {
            mapValue.put(content, moduleName);
        }
    }


    private static void putXmlBean(String lan, XmlBean xmlBean) {//语言对应的翻译列表
        if (languageXmlBeanMap.containsKey(lan) && null != languageXmlBeanMap.get(lan)) {
            List<XmlBean> xmlBeanList = languageXmlBeanMap.get(lan);
            xmlBeanList.add(xmlBean);
            languageXmlBeanMap.put(lan, xmlBeanList);
        } else {
            List<XmlBean> xmlBeanList = new ArrayList<>();
            xmlBeanList.add(xmlBean);
            languageXmlBeanMap.put(lan, xmlBeanList);
        }
    }
}
